これはインタラクティブなノートブックです。ローカルで実行するか、以下のリンクを使用してください:

🔑 前提条件

Weaveでトレースを開始する前に、以下の前提条件を完了してください。
  1. W&B Weave SDKをインストールし、あなたのAPI keyでログインします。
  2. OpenAI SDKをインストールし、あなたのAPI keyでログインします。
  3. W&Bプロジェクトを初期化します。
# Install dependancies and imports
!pip install wandb weave openai -q

import json
import os
from getpass import getpass

from openai import OpenAI

import weave

# 🔑 Setup your API keys
# Running this cell will prompt you for your API key with `getpass` and will not echo to the terminal.
#####
print("---")
print(
    "You can find your Weights and Biases API key here: https://wandb.ai/settings#api"
)
os.environ["WANDB_API_KEY"] = getpass("Enter your Weights and Biases API key: ")
print("---")
print("You can generate your OpenAI API key here: https://platform.openai.com/api-keys")
os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API key: ")
print("---")
#####

# 🏠 Enter your W&B project name
weave_client = weave.init("MY_PROJECT_NAME")  # 🐝 Your W&B project name

🐝 最初のトレースを実行する

以下のコードサンプルは、@weave.opデコレータを使用してWeaveでトレースをキャプチャして可視化する方法を示しています。これはextract_fruitという関数を定義し、OpenAIのGPT-4oにプロンプトを送信して文から構造化データ(果物、色、風味)を抽出します。この関数を@weave.opでデコレートすることで、Weaveは入力、出力、中間ステップを含む関数の実行を自動的に追跡します。サンプル文で関数が呼び出されると、完全なトレースが保存され、Weave UIで表示できます。
@weave.op()  # 🐝 Decorator to track requests
def extract_fruit(sentence: str) -> dict:
    client = OpenAI()
    system_prompt = (
        "Parse sentences into a JSON dict with keys: fruit, color and flavor."
    )
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": sentence},
        ],
        temperature=0.7,
        response_format={"type": "json_object"},
    )
    extracted = response.choices[0].message.content
    return json.loads(extracted)

sentence = "There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy."
extract_fruit(sentence)

🚀 さらに例を探していますか?